<template>
  <div class="add-work-container">
    <div class="wrapper">
      <el-form ref="form" :model="form" :rules="rules" class="work-form" :label-width="labelWidth">
        <!-- 比赛类型选择 -->
        <el-form-item label="比赛类型" required>
          <el-radio-group v-model="form.competitionType" class="competition-type-group" :disabled="isEdit === 2">
            <el-radio
              v-for="type in competitionTypeList"
              :key="type.id || `type_${$index}`"
              :label="type.id"
            >
              {{ type.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 关联虚拟用户 -->
        <el-form-item label="关联原创用户">
          <div class="virtual-user-section">
            <div v-if="form.virtualUserName" class="selected-user">
              <div class="selected-user-info">
                <div class="selected-user-avatar">
                  <img v-if="selectedUserAvatar && selectedUserAvatar !== '头像'" :src="selectedUserAvatar" alt="头像" class="avatar-image">
                  <i v-else class="el-icon-user"></i>
                </div>
                <div class="selected-user-details">
                  <div class="selected-user-name">{{ form.virtualUserName }}</div>
                </div>
                <el-button v-if="isEdit !== 2" type="text" class="remove-user-btn" @click="clearVirtualUser">
                  <i class="el-icon-close"></i>
                </el-button>
              </div>
            </div>
            <el-button v-if="isEdit !== 2 && !form.virtualUserName" type="primary" class="add-virtual-user-btn" @click="handleAddVirtualUser">
              <i class="el-icon-plus"></i>
            </el-button>
            <div v-if="isEdit === 2 && !form.virtualUserName" class="no-user-info">
              未关联虚拟用户
            </div>
          </div>
        </el-form-item>

        <!-- 作品图片 -->
        <el-form-item label="作品图片" required>
          <div class="upload-section">
            <div v-if="isEdit === 2" class="image-display-area">
              <div v-if="picList.length > 0" class="image-gallery">
                <div v-for="(image, index) in picList" :key="index" class="image-item">
                  <el-image
                    :src="image"
                    :preview-src-list="picList"
                    :initial-index="index"
                    fit="cover"
                    class="work-image"
                  />
                </div>
              </div>
              <div v-else class="no-images">暂无图片</div>
            </div>
            <div v-else class="image-upload-area">
              <self-upload
                v-model="picListJson"
                :multiple="true"
                :limit="18"
                class="work-upload"
              ></self-upload>
            </div>
            <div v-if="isEdit !== 2" class="upload-tip">
              注:最多可上传18张,上传的图片格式png、jpg、jpeg、webp,不支持gif、live及其转化后的格式,不限高宽比,不大于5MB。
            </div>
          </div>
        </el-form-item>

        <!-- 作品标题 -->
        <el-form-item label="作品标题" prop="title">
          <el-input 
            v-model="form.title" 
            placeholder="请输入作品标题" 
            maxlength="50" 
            show-word-limit
            class="work-title-input"
            :readonly="isEdit === 2"
          ></el-input>
        </el-form-item>

        <!-- 作品描述 -->
        <el-form-item label="作品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请详细描述您的作品创意"
            :rows="6"
            maxlength="500"
            show-word-limit
            class="work-description-input"
            :readonly="isEdit === 2"
          ></el-input>
        </el-form-item>

        <!-- 标签 -->
        <el-form-item label="">
          <div class="tags-section">
            <div class="tag-list">
              <el-tag
                v-for="tag in selectedTags"
                :key="tag.id || `fallback_${$index}`"
                :closable="isEdit !== 2"
                @close="handleCloseTag(tag)"
                class="tag-item"
              >
                {{ tag.name }}
              </el-tag>
              <el-button v-if="isEdit !== 2" type="primary" @click="getTag" class="add-tag-btn">#添加标签</el-button>
            </div>
          </div>
        </el-form-item>

        <!-- AI设计过程 -->
        <el-form-item label="AI设计过程:">
          <el-radio-group v-model="form.designType" class="design-process-group" :disabled="isEdit === 2">
            <el-radio label="3">非AI设计</el-radio>
            <el-radio label="1">纯AI设计</el-radio>
            <el-radio label="2">AI辅助设计</el-radio>
          </el-radio-group>
          <div v-if="isEdit !== 2" class="design-tip">
            版权类型涉及知识版权确权的分类,请按照创作方式选择对应选项
          </div>
        </el-form-item>


        <!-- AI工具 -->
        <el-form-item label="AI工具:">
          <div class="ai-tools-container">
            <div v-for="(tool, index) in form.aiTools" :key="index" class="ai-tool-item">
              <el-input
                v-model="form.aiTools[index]"
                placeholder="请输入工具名称"
                maxlength="50"
                show-word-limit
                class="ai-tool-input"
                :readonly="isEdit === 2"
              ></el-input>
              <el-button v-if="isEdit !== 2 && index > 0" type="danger" @click="removeAITool(index)" class="remove-tool-btn">
                -
              </el-button>
              <el-button v-if="isEdit !== 2 && index == 0" type="primary" @click="addAITool" class="add-tool-btn">
                +
              </el-button>
              <div v-else class="tool-btn-placeholder"></div>
            </div>
          </div>
        </el-form-item>

        <!-- 参与设计 -->
        <el-form-item label="参与设计:">
          <div class="designers-container">
            <div v-for="(designer, index) in form.designers" :key="index" class="designer-item">
              <el-input
                v-model="form.designers[index]"
                placeholder="请输入设计师名称"
                maxlength="50"
                show-word-limit
                class="designer-input"
                :readonly="isEdit === 2"
              ></el-input>
              <el-button v-if="isEdit !== 2 && index > 0" type="danger" @click="removeDesigner(index)" class="remove-tool-btn">
                -
              </el-button>
              <el-button v-if="isEdit !== 2 && index == 0" type="primary" @click="addDesigner" class="add-tool-btn">
                +
              </el-button>
              <div v-else class="tool-btn-placeholder"></div>
            </div>
          </div>
        </el-form-item>

        <!-- 是否禁止评论 -->
        <el-form-item label="是否禁止评论">
          <div class="comment-status-section">
            <el-switch 
              v-model="form.forbidComment" 
              :disabled="isEdit === 2 || isPlatformCommentDisabled"
              :active-text="isPlatformCommentDisabled ? '平台已关闭评论' : ''"
            />
            <span v-if="isPlatformCommentDisabled" class="platform-disabled-tip">
              平台已关闭评论功能
            </span>
          </div>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item v-if="isEdit !== 2">
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading" class="submit-btn">
            {{ isEdit === 1 ? '更新' : '提交' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 标签选择对话框 -->
    <el-dialog 
      :visible.sync="tagDialogVisible" 
      width="800px" 
      :before-close="() => tagDialogVisible = false"
      :append-to-body="true"
      :modal="true"
      custom-class="tag-select-dialog"
    >
      <div class="tag-dialog-content">
        <!-- 推荐标签 -->
        <div class="tag-section">
          <h4 class="tag-section-title">推荐标签</h4>
          <div class="tag-list">
            <el-tag
              v-for="tag in hotTags"
              :key="tag.id || `hot_${$index}`"
              :type="isTagSelected(tag) ? 'primary' : 'default'"
              :closable="isTagSelected(tag)"
              @click="selectTag(tag)"
              @close.stop="selectTag(tag)"
              class="tag-item"
              :class="{ 'is-selected': isTagSelected(tag) }"
              :style="getTagStyle(tag)"
            >
              {{ tag.name }}
            </el-tag>
          </div>
        </div>

        <!-- 全部标签 -->
        <div class="tag-section">
          <h4 class="tag-section-title">全部标签</h4>
          <div class="tag-list">
            <el-tag
              v-for="tag in AllTagList"
              :key="tag.id || `all_${$index}`"
              :type="isTagSelected(tag) ? 'primary' : 'default'"
              :closable="isTagSelected(tag)"
              @click="selectTag(tag)"
              @close.stop="selectTag(tag)"
              class="tag-item"
              :class="{ 'is-selected': isTagSelected(tag) }"
              :style="getTagStyle(tag)"
            >
              {{ tag.name }}
            </el-tag>
          </div>
        </div>

        <!-- 已选择标签显示 -->
        <div class="selected-tags-info">已选择 {{ tempSelectedTags.length }}/3 个标签</div>
      </div>
      <template #footer>
        <el-button @click="tagDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmTags">确定</el-button>
      </template>
      <!-- 头部 -->
      <template #title>
        <div style="font-size: 22px; margin-left: 20px" class="dialog-title">选择标签</div>
      </template>
    </el-dialog>

    <el-dialog 
      :visible.sync="rulesDialogVisible" 
      title="参赛者规范" 
      width="100%" 
      :before-close="closeRulesDialog"
      :append-to-body="false"
      :modal="false"
      custom-class="child-dialog"
    >
      <template #title>
        <div style="font-size: 22px; margin-left: 20px" class="dialog-title">参赛者规范</div>
      </template>
      <div
        class="rules-content"
        v-html="contestantRulesContent ? contestantRulesContent.replace(/<br\/>/gi, '') : ''"
      ></div>
      <template #footer>
        <el-button @click="closeRulesDialog">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 用户选择对话框 -->
    <el-dialog 
      :visible.sync="userDialogVisible" 
      title="选择虚拟用户" 
      width="800px"
      :before-close="closeUserDialog"
      :modal="false"
      :append-to-body="false"
      :close-on-click-modal="false"
      top="5vh"
      custom-class="user-select-dialog"
    >
      <div v-loading="userListLoading" class="user-list-container">
        <div v-if="userList.length === 0 && !userListLoading" class="no-users">
          暂无可用用户
        </div>
        <div v-else class="user-grid">
          <div 
            v-for="user in userList" 
            :key="user.euserId" 
            class="user-item"
            @click="selectUser(user)"
          >
            <div class="user-avatar">
              <img v-if="user.avatar && user.avatar !== '头像'" :src="user.avatar" alt="头像" class="avatar-image">
              <i v-else class="el-icon-user"></i>
            </div>
            <div class="user-info">
              <div class="user-name">{{ user.playerName || '未命名用户' }}</div>
              <div class="user-id">ID: {{ user.euserId }}</div>
              <div class="user-email">{{ user.emailAccount }}</div>
            </div>
          </div>
        </div>
        
        <!-- 分页组件 -->
        <div v-if="userList.length > 0" class="user-pagination">
          <el-pagination
            @size-change="handleUserSizeChange"
            @current-change="handleUserCurrentChange"
            :current-page="userPagination.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="userPagination.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="userPagination.total"
          />
        </div>
      </div>
      <template #footer>
        <el-button @click="closeUserDialog">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// +---------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +---------------------------------------------------------------------
// | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
// +---------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +---------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +---------------------------------------------------------------------

import selfUpload from '@/components/base/selfUpload.vue'
import { uploadImageApi } from '@/api/user'
import * as community from '@/api/community'
import request from '@/utils/request'

export default {
  name: 'EditVirtualWork',
  components: {
    selfUpload
  },
  props: {
    isEdit: {
      type: Number,
      default: 0 // 0=添加 1=编辑
    },
    editData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      labelWidth: '140px',
      submitLoading: false,
      uploadUrl: process.env.VUE_APP_BASE_API + '/admin/platform/upload/image',
      playType: '',
      agreementChecked: false,
      agreementChecked2: false,
      
      // 图片上传相关
      picList: [],
      picListJson: '[]',
      
      // 标签相关
      selectedTags: [],
      tempSelectedTags: [],
      hotTags: [],
      AllTagList: [],
      
      // 比赛类型列表
      competitionTypeList: [],
      
      // 参赛者规范对话框
      rulesDialogVisible: false,
      contestantRulesContent: '',
      
      // 标签对话框状态
      tagDialogVisible: false,
      
      // 用户列表相关
      userList: [],
      userListLoading: false,
      userDialogVisible: false,
      userPagination: {
        page: 1,
        limit: 10,
        total: 0
      },
      
      form: {
        id: null,
        title: '',
        description: '',
        designType: '3', // 默认非AI设计
        forbidComment: false,
        competitionType: '1', // 添加比赛类型字段，默认值为1
        aiTools: [], // AI工具数组
        designers: [], // 参与设计人数组
        virtualUserId: null, // 关联的虚拟用户ID
        virtualUserName: '', // 关联的虚拟用户名称
      },
      selectedUserAvatar: '', // 选中用户的头像
      rules: {
        title: [
          { required: true, message: '请输入作品标题', trigger: 'blur' },
          { min: 1, max: 50, message: '标题长度在1到50个字符', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入作品描述', trigger: 'blur' },
          { min: 1, max: 500, message: '描述长度在1到500个字符', trigger: 'blur' },
        ],
      }
    };
  },
  computed: {
    // 判断是否为平台关闭评论状态
    isPlatformCommentDisabled() {
      // 检查原始数据中的replyStatus是否为3（平台关闭）
      return this.editData.replyStatus === 3;
    }
  },
  mounted() {
    // 初始化响应式尺寸
    this.handleResize()
    // 添加窗口大小改变监听
    window.addEventListener('resize', this.handleResize)

    // 初始化第一个AI工具输入框
    if (this.form.aiTools.length === 0) {
      this.form.aiTools.push('')
    }

    // 初始化第一个参与设计人输入框
    if (this.form.designers.length === 0) {
      this.form.designers.push('')
    }

    // 预加载比赛类型列表，避免后续重复请求
    this.fetchCompetitionTypes().catch(error => {
      // 预加载失败，不影响后续功能
    });

    // 确保所有标签数据都是安全的
    this.sanitizeTagData();

    // 手动监听 editData 变化
    this.$watch('editData', async (newVal, oldVal) => {
      if (newVal && Object.keys(newVal).length > 0) {
        // 如果还在loading中，不处理数据
        if (newVal.loading) {
          return;
        }

        // 在处理数据前先清理标签数据
        this.sanitizeTagData();

        try {
          // 确保比赛类型列表已加载（通常预加载已完成）
          if (this.competitionTypeList.length === 0) {
            await this.fetchCompetitionTypes();
          }

          // 处理编辑数据
          this.handleEditData(newVal);

          // 强制触发视图更新
          this.$nextTick(() => {
            this.$forceUpdate();
          });

        } catch (error) {
          this.$message.error('数据加载失败，请重试');
        }
      }
    }, { immediate: true, deep: true }); // 恢复immediate，确保初始化时也处理数据
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },
  watch: {
    picListJson: {
      handler(newVal) {
        try {
          this.picList = JSON.parse(newVal || '[]')
        } catch (e) {
          this.picList = []
        }
      },
      immediate: true
    }
  },
  methods: {
    // 处理编辑数据的方法
    handleEditData(newVal) {
      // 处理图片数据
      if (newVal.image) {
        this.picList = newVal.image.split(',').filter(img => img.trim());
        this.picListJson = JSON.stringify(this.picList);
      }
      
      // 处理AI工具数据
      let aiTools = [''];
      if (newVal.aitool && newVal.aitool !== '0') {
        aiTools = newVal.aitool.split(',').filter(tool => tool.trim());
        if (aiTools.length === 0) aiTools = [''];
      }
      
      // 处理参与设计人数据
      let designers = [''];
      if (newVal.player && newVal.player !== '0') {
        designers = newVal.player.split(',').filter(designer => designer.trim());
        if (designers.length === 0) designers = [''];
      }
      
      // 处理标签数据 - 增强错误处理
      if (newVal.topicIds && newVal.topicIds !== '0' && newVal.topicIds !== '') {
        try {
          const tagIds = newVal.topicIds.split(',').filter(id => id && id.trim() !== '');
          if (tagIds.length > 0) {
            this.fetchTagInfoByIds(tagIds);
          } else {
            this.selectedTags = [];
          }
        } catch (error) {
          this.selectedTags = [];
        }
      } else {
        this.selectedTags = [];
      }

          // 修正后的核心逻辑：将 replyStatus 转换为 forbidComment
          // replyStatus = 1 (开启评论) -> forbidComment = false (允许)
          // replyStatus = 2 (关闭评论) -> forbidComment = true (禁止)
          // replyStatus = 3 (平台关闭) -> forbidComment = true (禁止)

          const forbidCommentValue = newVal.replyStatus === 2 || newVal.replyStatus === 3 ||
                                    newVal.replyStatus === '2' || newVal.replyStatus === '3';

          this.form = {
            ...this.form,
            ...newVal,
            title: newVal.title || '',
            // 只有当content有值时才设置description，避免空值覆盖已有数据
            ...(newVal.content ? { description: newVal.content } : {}),
            forbidComment: forbidCommentValue,
            aiTools: aiTools,
            designers: designers,
            competitionType: (() => {
              if (newVal.competitionType) {
                return newVal.competitionType;
              } else if (newVal.categoryId) {
                const categoryIdStr = newVal.categoryId.toString();
                return categoryIdStr;
              } else if (this.competitionTypeList.length > 0) {
                return this.competitionTypeList[0].id;
              } else {
                return '1';
              }
            })(),
            designType: newVal.designType || (newVal.designProcess ? newVal.designProcess.toString() : '3'),
            virtualUserId: newVal.euserId || null,
            virtualUserName: newVal.virtualUserName || newVal.authorName || ''
          };


          // 强制触发视图更新
          this.$forceUpdate();

          // 强制触发响应式更新
          this.$nextTick(() => {
          });
      
          // 如果有euserId，需要获取用户详细信息来回显头像和名字
          if (newVal.euserId) {
            this.fetchUserInfoById(newVal.euserId);
          } else {
            this.selectedUserAvatar = '';
          }
    },
    // 添加响应式调整函数
    handleResize() {
      const width = window.innerWidth
      if (width < 768) {
        // 移动端
        this.labelWidth = '100%'
      } else if (width < 1200) {
        // 平板端
        this.labelWidth = '120px'
      } else {
        // 桌面端
        this.labelWidth = '140px'
      }
    },
    
    
    // 标签相关
    handleCloseTag(tag) {
      const index = this.selectedTags.findIndex((t) => t.id === tag.id)
      if (index !== -1) {
        this.selectedTags.splice(index, 1)
      }
    },
    
    // 获取参赛者规范内容
    async fetchContestantRules() {
      try {
        // 模拟API调用
        this.contestantRulesContent = '<h3>参赛者规范</h3><p>1. 参赛作品必须为原创设计，不得侵犯他人知识产权。</p><p>2. 参赛者需保证作品内容的真实性和合法性。</p><p>3. 主办方有权对参赛作品进行审核和展示。</p>'
      } catch (error) {
        this.$message.error('获取参赛者规范失败')
      }
    },
    
    // 获取比赛类型列表
    async fetchCompetitionTypes() {
      // 如果已经加载过，直接返回
      if (this.competitionTypeList.length > 0) {
        return Promise.resolve();
      }

      try {
        const res = await community.communityCategoryListApi()
        // 只获取启用的分类数据
        this.competitionTypeList = (res.list || [])
          .filter(item => item && item.isShow === 1 && item.id != null && item.id !== undefined) // 过滤掉无效的id
          .map(item => ({
            id: item.id.toString(), // 确保ID是字符串格式
            name: item.name
          }))

        // 只有在添加模式时才设置默认值，编辑模式保持原有值
        if (this.competitionTypeList.length > 0 && this.isEdit === 0) {
          this.form.competitionType = this.competitionTypeList[0].id
        }

        return Promise.resolve(); // 返回Promise表示加载完成
      } catch (error) {
        this.$message.error('获取比赛类型失败')
        return Promise.reject(error);
      }
    },
    
    // 点击参赛者规范文本时执行
    async handleRulesClick() {
      await this.fetchContestantRules()
      this.rulesDialogVisible = true
    },
    
    // 关闭参赛者规范对话框
    closeRulesDialog() {
      this.rulesDialogVisible = false
    },
    
    // 获取标签并打开对话框
    getTag() {
      // 获取推荐标签（isHot=1的标签）
      community.communityTopicListApi({
        page: 1,
        limit: 100,
        isHot: 1
      }).then((res) => {
        // 过滤掉无效id的标签，确保所有标签都有有效的id
        this.hotTags = (res.list || []).filter(tag => {
          const validId = tag.id != null && tag.id !== undefined && !isNaN(tag.id);
          // 过滤掉无效id的推荐标签
          return validId;
        });

        // 获取全部标签
        return community.communityTopicListApi({
          page: 1,
          limit: 100
        })
      }).then((res) => {
        // 过滤掉无效id的标签，确保所有标签都有有效的id
        this.AllTagList = (res.list || []).filter(tag => {
          const validId = tag.id != null && tag.id !== undefined && !isNaN(tag.id);
          // 过滤掉无效id的全部标签
          return validId;
        });
        // 初始化临时选中标签数组为当前已选中的标签
        // 确保tempSelectedTags中的标签对象和对话框中的标签对象结构一致
        this.tempSelectedTags = this.selectedTags.map(selectedTag => {
          // 尝试在对话框的标签列表中找到对应的完整标签对象
          const fullTag = [...this.hotTags, ...this.AllTagList].find(tag =>
            (typeof tag.id === 'string' ? parseInt(tag.id) : tag.id) ===
            (typeof selectedTag.id === 'string' ? parseInt(selectedTag.id) : selectedTag.id)
          )

          if (fullTag) {
            // 使用完整的标签对象
            return { ...fullTag }
          } else {
            // 如果找不到，使用selectedTag，但确保id有效
            const safeId = selectedTag.id != null && selectedTag.id !== undefined && !isNaN(selectedTag.id)
              ? selectedTag.id
              : `safe_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

            return {
              id: safeId,
              name: selectedTag.name,
              isHot: false,
              ...selectedTag
            }
          }
        })

        // 打开对话框
        this.tagDialogVisible = true
      }).catch((err) => {
        this.$message.error('获取标签失败，请稍后重试')
      })
    },
    
    // 在对话框中选择标签
    selectTag(tag) {
      const index = this.tempSelectedTags.findIndex((t) => t.id === tag.id)
      if (index !== -1) {
        // 取消选择
        this.tempSelectedTags.splice(index, 1)
      } else if (this.tempSelectedTags.length < 3) {
        // 添加选择
        this.tempSelectedTags.push(tag)
      } else {
        this.$message.warning('最多添加3个标签')
      }
      // 强制更新视图
      this.$forceUpdate()
    },
    
    // 检查标签是否被选中
    isTagSelected(tag) {
      const isSelected = this.tempSelectedTags.some((t) => {
        // 确保ID类型一致，进行比较
        const tagId = typeof tag.id === 'string' ? parseInt(tag.id) : tag.id
        const tempTagId = typeof t.id === 'string' ? parseInt(t.id) : t.id
        return tempTagId === tagId
      })
      return isSelected
    },
    
    // 获取标签样式
    getTagStyle(tag) {
      if (this.isTagSelected(tag)) {
        return {
          backgroundColor: '#FF6600',
          borderColor: '#FF6600',
          color: '#ffffff'
        }
      }
      return {}
    },
    
    // 确认选择标签 - 只有点击确定后才更新到页面上
    confirmTags() {
      // 将临时选中的标签更新到页面显示的标签数组中
      this.selectedTags = [...this.tempSelectedTags]
      this.tagDialogVisible = false
    },
    
    // 添加新的AI工具
    addAITool() {
      this.form.aiTools.push('')
    },
    
    // 删除AI工具
    removeAITool(index) {
      this.form.aiTools.splice(index, 1)
    },
    
    // 添加参与设计人
    addDesigner() {
      this.form.designers.push('')
    },
    
    // 删除参与设计人
    removeDesigner(index) {
      this.form.designers.splice(index, 1)
    },
    
    // 确保所有标签数据都是安全的，防止NaN key
    sanitizeTagData() {
      // 清理selectedTags
      if (this.selectedTags && Array.isArray(this.selectedTags)) {
        this.selectedTags = this.selectedTags.filter(tag => {
          return tag && tag.id != null && tag.id !== undefined && !isNaN(tag.id);
        });
      }

      // 清理hotTags
      if (this.hotTags && Array.isArray(this.hotTags)) {
        this.hotTags = this.hotTags.filter(tag => {
          return tag && tag.id != null && tag.id !== undefined && !isNaN(tag.id);
        });
      }

      // 清理AllTagList
      if (this.AllTagList && Array.isArray(this.AllTagList)) {
        this.AllTagList = this.AllTagList.filter(tag => {
          return tag && tag.id != null && tag.id !== undefined && !isNaN(tag.id);
        });
      }
    },

    // 根据用户ID获取用户信息
    async fetchUserInfoById(userId) {
      try {
        const res = await community.communityAddVirtualListApi({ applyTypes: -1 })
        const userList = res.list || []
        const user = userList.find(u => u.euserId === userId)
        
        if (user) {
          this.form.virtualUserName = user.playerName || ''
          this.selectedUserAvatar = user.avatar || ''
        } else {
          this.form.virtualUserName = ''
          this.selectedUserAvatar = ''
        }
      } catch (error) {
        // 获取用户信息失败，不影响功能
        this.form.virtualUserName = ''
        this.selectedUserAvatar = ''
      }
    },

    // 根据标签ID获取标签信息
    async fetchTagInfoByIds(tagIds) {
      try {
        const res = await community.communityTopicListApi({ page: 1, limit: 1000 })
        const allTags = res.list || []
        const selectedTags = []

        tagIds.forEach((id, index) => {
          // 过滤无效的ID
          if (!id || id === '' || id === '0' || id === 'null' || id === 'undefined') {
            return;
          }

          const parsedId = parseInt(id);
          if (isNaN(parsedId) || parsedId <= 0) {
            return;
          }

          const tag = allTags.find(t => t.id === parsedId)
          if (tag) {
            // 确保tag.id是有效的
            const validTagId = (tag.id != null && tag.id !== undefined && !isNaN(tag.id)) ? tag.id : `api_tag_${Date.now()}_${index}`;

            // 保持和对话框标签对象完全一致的结构
            selectedTags.push({
              id: validTagId,
              name: tag.name,
              // 如果API返回的标签对象有其他属性，也要包含进来
              ...tag
            })
          } else {
            // 如果找不到标签，创建一个完整的标签对象结构
            const validId = `tag_${Date.now()}_${index}`;

            selectedTags.push({
              id: validId,
              name: `标签${id}`,
              // 添加其他可能的属性，保持结构一致性
              isHot: false
            })
          }
        })

        this.selectedTags = selectedTags
      } catch (error) {
        // 如果API调用失败，使用默认标签名称，确保id有效
        this.selectedTags = tagIds.map((id, index) => {
          const defaultTag = {
            id: !isNaN(parseInt(id)) && parseInt(id) > 0 ? parseInt(id) : `fallback_${Date.now()}_${index}`,
            name: `标签${id}`
          };
          return defaultTag;
        });
      }
    },

    // 添加虚拟用户
    async handleAddVirtualUser() {
      this.userListLoading = true
      this.userDialogVisible = true
      // 重置分页
      this.userPagination.page = 1
      this.userPagination.limit = 10
      await this.fetchUserList()
    },
    
    // 获取用户列表（支持分页）
    async fetchUserList() {
      this.userListLoading = true
      try {
        const params = {
          applyTypes: -1,
          page: this.userPagination.page,
          limit: this.userPagination.limit
        }
        const res = await community.communityAddVirtualListApi(params)
        this.userList = res.list || []
        this.userPagination.total = res.total || 0
      } catch (error) {
        // 获取用户列表失败，不影响功能
        this.$message.error('获取用户列表失败')
      } finally {
        this.userListLoading = false
      }
    },
    
    // 选择用户
    selectUser(user) {
      this.form.virtualUserId = user.euserId
      this.form.virtualUserName = user.playerName
      this.selectedUserAvatar = user.avatar || ''
      this.userDialogVisible = false
      this.$message.success(`已选择用户: ${user.playerName}`)
    },
    
    // 关闭用户选择对话框
    closeUserDialog() {
      this.userDialogVisible = false
    },
    
    // 用户列表分页大小改变
    handleUserSizeChange(val) {
      this.userPagination.limit = val
      this.userPagination.page = 1
      this.fetchUserList()
    },
    
    // 用户列表当前页改变
    handleUserCurrentChange(val) {
      this.userPagination.page = val
      this.fetchUserList()
    },
    
    // 清除虚拟用户
    clearVirtualUser() {
      this.form.virtualUserId = null
      this.form.virtualUserName = ''
      this.selectedUserAvatar = ''
    },
    
    // 检查AI工具是否全部填写
    areAIToolsValid() {
      if ((this.form.designType === '1' || this.form.designType === '2') && this.form.aiTools.length === 0) {
        this.$message.warning('请至少添加一个AI工具')
        return false
      }

      // 检查所有AI工具是否都已填写
      for (const tool of this.form.aiTools) {
        if (!tool.trim() || tool.length > 50) {
          this.$message.warning('AI工具名称不能为空且长度不能超过50个字符')
          return false
        }
      }

      return true
    },
    
    // 检查参与设计人是否全部填写
    areDesignersValid() {
      if (this.form.designers.length === 0) {
        this.$message.warning('请至少添加一个参与设计人')
        return false
      }

      // 检查所有参与设计人是否都已填写
      for (const designer of this.form.designers) {
        if (!designer.trim() || designer.length > 50) {
          this.$message.warning('参与设计人名称不能为空且长度不能超过50个字符')
          return false
        }
      }

      return true
    },
    
    // 提交
    async handleSubmit() {
      
      await this.$refs.form.validate(async (valid, fields) => {
        if (valid) {
          // 只验证最基本的必填字段
          if (this.picList.length === 0) {
            return this.$message.warning('请上传作品图片')
          }

          // 移除协议验证，因为图片中没有显示协议选项
          

          // 准备提交数据 - 按照API接口参数格式
          const submitData = {
            id: this.form.id || 0, // 作品ID，编辑时需要
            title: this.form.title || '', // 作品标题
            type: 1, // 1图文，2视频
            cover: this.picList[0] || '', // 封面图片
            image: this.picList.join(',') || '', // 图片列表，用逗号分隔
            video: '', // 视频地址，图文类型为空
            content: this.form.description || '', // 作品描述
            categoryId: parseInt(this.form.competitionType) || 0, // 分类ID，转换为数字
            topicIds: this.selectedTags.length > 0 ? this.selectedTags.map((tag) => tag.id).join(',') : '0', // 标签ID，用逗号分隔，没有则传0
            designProcess: parseInt(this.form.designType) || 0, // 设计过程，转换为数字
            aitool: this.form.aiTools.length > 0 ? this.form.aiTools.join(',') : '0', // AI工具，用逗号分隔，没有则传0
            player: this.form.designers.length > 0 ? this.form.designers.join(',') : '0', // 参与设计人，用逗号分隔，没有则传0
            euserId: this.form.virtualUserId || 0, // 关联虚拟用户ID
            auditStatus: 0, // 审核状态
            replyStatus: (() => {
              // 如果原始数据是平台关闭状态，保持不变
              if (this.editData && this.editData.replyStatus === 3) {
                return 3;
              }
              // 否则根据开关状态设置：forbidComment为true表示禁止评论，对应replyStatus=2（关闭）
              return this.form.forbidComment ? 2 : 1;
            })() // 评论状态，1-开启，2-关闭，3-平台关闭
          }

          try {
            this.submitLoading = true
            
            let res;
            if (this.isEdit === 1) {
              // 编辑模式 - 调用更新API
              res = await request.post('/admin/platform/virtual/community/update', submitData)
              this.$message.success('作品更新成功')
            } else {
              // 添加模式 - 调用创建API
              res = await request.post('/admin/platform/virtual/community/create', submitData)
              this.$message.success('作品提交成功')
            }
            
            this.$emit('hideDialog')
            this.submitLoading = false
          } catch (error) {
            // 作品提交失败
            this.submitLoading = false
            this.$message.error(this.isEdit === 1 ? '作品更新失败，请重试' : '作品提交失败，请重试')
          }
        }
      })
    },
    
    // 取消
    handleCancel() {
      this.$emit('hideDialog');
    }
  }
};
</script>

<style scoped lang="scss">
.add-work-container {
  padding: 20px 0;
  background-color: #ffffff;
  min-height: 100vh;
}

.wrapper {
  margin: 0;
  max-width: 66.67%;
  background-color: #fff;
  padding: 20px;
  border-radius: 0;
  box-shadow: none;

  // 比赛类型选择样式
  .competition-type-group {
    .el-radio {
      margin-right: 30px;
    }
  }

  // 虚拟用户按钮样式
  .virtual-user-section {
    display: flex;
    align-items: center;
    gap: 10px;
    
    .selected-user {
      .selected-user-info {
        display: flex;
        align-items: center;
        height: 40px;
        padding: 0 12px;
        background-color: #f0f9ff;
        border: 1px solid #b3d8ff;
        border-radius: 6px;
        gap: 10px;
        
        .selected-user-avatar {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          background-color: #f5f7fa;
          display: flex;
          align-items: center;
          justify-content: center;
          overflow: hidden;
          
          .avatar-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          
          .el-icon-user {
            font-size: 16px;
            color: #909399;
          }
        }
        
        .selected-user-details {
          flex: 1;
          
          .selected-user-name {
            font-size: 13px;
            font-weight: 500;
            color: #303133;
          }
        }
        
        .remove-user-btn {
          color: #f56c6c;
          font-size: 14px;
          padding: 2px;
          
          &:hover {
            color: #f78989;
          }
        }
      }
    }
    
    .add-virtual-user-btn {
      width: 60px;
      height: 60px;
      border-radius: 8px;
      font-size: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .no-user-info {
      color: #999;
      font-size: 14px;
      padding: 20px 0;
      text-align: center;
    }
  }

  // 图片上传区域样式
  .image-upload-area {
    .work-upload {
      :deep(.el-upload) {
        width: 100px !important;
        height: 100px !important;
        border: 2px dashed #d9d9d9;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #fafafa;
        
        &:hover {
          border-color: #409eff;
        }
      }
    }
  }

  // 图片展示区域样式
  .image-display-area {
    .image-gallery {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
      gap: 15px;
      margin-bottom: 10px;
      
      .image-item {
        .work-image {
          width: 100%;
          height: 120px;
          border-radius: 8px;
          cursor: pointer;
          border: 1px solid #e4e7ed;
        }
      }
    }
    
    .no-images {
      text-align: center;
      color: #999;
      padding: 40px 0;
      font-size: 14px;
    }
  }

  // 标签样式
  .tag-list {
    margin-bottom: 15px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px;
  }

  .tag-item {
    background-color: #f0f9eb;
    border-color: #d9f7be;
    color: #52c41a;
    border-radius: 4px;
    padding: 4px 8px;
    font-size: 12px;
    margin-right: 8px;
    margin-bottom: 8px;
  }

  .add-tag-btn {
    background-color: #1890ff;
    border-color: #1890ff;
    color: #fff;
    border-radius: 4px;
    padding: 4px 12px;
    font-size: 12px;
    height: 28px;
    line-height: 1;
  }

  // AI设计过程样式
  .design-process-group {
    .el-radio {
      margin-right: 30px;
    }
  }

  .design-tip {
    font-size: 12px;
    color: #666;
    margin-top: 8px;
    line-height: 1.4;
  }

  // AI工具和参与设计样式
  .ai-tools-container,
  .designers-container {
    width: 100%;
  }

  .ai-tool-item,
  .designer-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    flex-wrap: wrap;
  }

  .ai-tool-input,
  .designer-input {
    flex: 1;
    margin-right: 10px;
    
    :deep(.el-input__inner) {
      height: 32px;
      line-height: 32px;
    }
  }

  .remove-tool-btn {
    height: 32px;
    width: 32px;
    padding: 0;
    margin-left: 10px;
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .add-tool-btn {
    height: 32px;
    width: 32px;
    padding: 0;
    margin-left: 10px;
    background-color: #1890ff;
    border-color: #1890ff;
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .tool-btn-placeholder {
    width: 32px;
    margin-left: 10px;
  }

  // 提交按钮样式
  .submit-btn {
    width: 33.33%;
    height: 48px;
    background-color: #1890ff;
    border-color: #1890ff;
    font-size: 16px;
    font-weight: 500;
    border-radius: 6px;
    margin-top: 20px;
  }

  .submit-btn:hover {
    background-color: #40a9ff;
    border-color: #40a9ff;
  }

  // 统一输入框高度
  .work-title-input,
  .work-description-input {
    :deep(.el-input__inner) {
      height: 40px;
      line-height: 40px;
    }
  }

  .work-description-input {
    :deep(.el-textarea__inner) {
      min-height: 120px;
      line-height: 1.5;
    }
  }

  // 减小标签对话框相关间距
  .tag-dialog-content {
    max-height: 350px; /* 原400px */
    overflow-y: auto;
  }

  .tag-section {
    margin-bottom: 15px; /* 原20px */
  }

  .tag-section-title {
    font-size: 15px; /* 原16px */
    font-weight: 500;
    margin-bottom: 8px; /* 原10px */
    color: #333;
  }

  // 调整AI工具相关间距和尺寸
  .ai-tool-first-row {
    display: flex;
    align-items: center;
    margin-bottom: 8px; /* 原10px */
  }

  .ai-tool-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px; /* 原10px */
    flex-wrap: wrap;
  }

  .remove-tool-btn {
    height: 36px; /* 原40px */
    width: 36px; /* 原40px */
    padding: 0;
    margin-left: 8px; /* 原10px */
  }

  .add-tool-btn {
    height: 36px; /* 原40px */
    margin-left: 8px; /* 原10px */
    background-color: #1890ff;
    border-color: #1890ff;
  }

  // 进一步减小移动端尺寸
  @media screen and (max-width: 768px) {
    padding: 12px; /* 原15px */


    .upload-tip,
    .design-tip {
      font-size: 10px; /* 原11px */
    }

    .selected-tags-info {
      font-size: 11px; /* 原12px */
    }

    .submit-btn {
      font-size: 13px; /* 原14px */
      width: 100%;
    }

    // Element Plus组件文字大小进一步调整
    :deep(.el-form-item__label) {
      font-size: 12px; /* 原13px */
    }

    :deep(.el-input__inner),
    :deep(.el-textarea__inner) {
      font-size: 12px; /* 原13px */
    }

    :deep(.el-radio__label),
    :deep(.el-checkbox__label) {
      font-size: 12px; /* 原13px */
    }

    :deep(.el-tag) {
      font-size: 11px; /* 原12px */
    }

    :deep(.el-button) {
      font-size: 12px; /* 原13px */
    }

    // 对话框文字大小进一步调整
    .dialog-title {
      font-size: 16px; /* 原18px */
    }

    .tag-section-title {
      font-size: 13px; /* 原14px */
    }
  }

  // 平板端适配进一步优化
  @media screen and (max-width: 1200px) {
    width: 98%;
    padding: 15px; /* 原20px */


    .submit-btn {
      font-size: 14px; /* 原15px */
    }
  }
}

.upload-section {
  width: 100%;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 10px;
}

.tags-section {
  width: 100%;
}

.tag-list {
  margin-bottom: 15px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.add-tag-btn {
  margin-bottom: 8px;
}

.selected-tags-info {
  margin-top: 20px;
  padding: 12px 16px;
  background: #f0f9ff;
  color: #1890ff;
  font-size: 14px;
  font-weight: 500;
  border-radius: 6px;
  text-align: center;
  border: 1px solid #d6f7ff;
}

.submit-btn {
  width: 200px;
  height: 40px;
  background-color: #ff6b6b;
  border-color: #ff6b6b;
  font-size: 16px;
}

.submit-btn:hover {
  background-color: #ff5252;
  border-color: #ff5252;
}

/* 标签对话框样式 */
.tag-dialog-content {
  max-height: 500px;
  overflow-y: auto;
  padding: 20px;
  background: #ffffff;
}

.tag-section {
  margin-bottom: 25px;
  background: #fafafa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e8e8e8;
}

.tag-section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #333;
  display: flex;
  align-items: center;
}

.tag-section-title::before {
  content: '';
  width: 3px;
  height: 16px;
  background: #FF6600;
  margin-right: 8px;
  border-radius: 2px;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 12px;
  align-items: flex-start;
}

.tag-item {
  cursor: pointer;
  transition: all 0.2s ease;
  border-radius: 16px;
  font-weight: 500;
  padding: 6px 12px;
  font-size: 13px;
  margin: 0;
  flex-shrink: 0;
  max-width: 120px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
  line-height: 1.2;
}

.tag-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 适配Element Plus组件样式 */
:deep(.el-upload-list__item) {
  width: 100px !important;
  height: 100px !important;
}

:deep(.el-upload) {
  width: 100px !important;
  height: 100px !important;
}

:deep(.el-checkbox) {
  margin-bottom: 15px;
}

:deep(.el-radio) {
  margin-right: 30px;
}

:deep(.el-tag) {
  margin-bottom: 8px;
}

/* 修改标签样式 - 未选中标签为浅灰色 */
:deep(.el-tag--default) {
  background-color: #f5f5f5;
  border-color: #d9d9d9;
  color: #666666;
  border-radius: 20px;
  font-weight: 500;
  padding: 6px 12px;
  font-size: 13px;
  max-width: 120px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
  line-height: 1.2;
}

:deep(.el-tag--default:hover) {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

/* 选中标签 - 橙色 #FF6600 */
:deep(.el-tag--primary) {
  background-color: #FF6600 !important;
  border-color: #FF6600 !important;
  color: #ffffff !important;
  border-radius: 20px;
  font-weight: 600;
  padding: 6px 12px;
  font-size: 13px;
  max-width: 120px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
  line-height: 1.2;
  box-shadow: 0 2px 6px rgba(255, 102, 0, 0.3);
}

:deep(.el-tag--primary:hover) {
  background-color: #ff8533 !important;
  border-color: #ff8533 !important;
  color: #ffffff !important;
  transform: translateY(-1px);
  box-shadow: 0 3px 10px rgba(255, 102, 0, 0.4);
}

/* 确保标签选择对话框中的选中标签样式 */
:deep(.tag-select-dialog .el-tag--primary) {
  background-color: #FF6600 !important;
  border-color: #FF6600 !important;
  color: #ffffff !important;
}

:deep(.tag-select-dialog .el-tag--primary:hover) {
  background-color: #ff8533 !important;
  border-color: #ff8533 !important;
  color: #ffffff !important;
}

/* 更具体的选择器确保样式生效 */
:deep(.tag-dialog-content .el-tag--primary) {
  background-color: #FF6600 !important;
  border-color: #FF6600 !important;
  color: #ffffff !important;
}

:deep(.tag-dialog-content .el-tag--primary:hover) {
  background-color: #ff8533 !important;
  border-color: #ff8533 !important;
  color: #ffffff !important;
}

/* 针对标签项的选中状态 */
:deep(.tag-item.el-tag--primary) {
  background-color: #FF6600 !important;
  border-color: #FF6600 !important;
  color: #ffffff !important;
}

:deep(.tag-item.el-tag--primary:hover) {
  background-color: #ff8533 !important;
  border-color: #ff8533 !important;
  color: #ffffff !important;
}

/* 使用自定义类确保选中状态 */
:deep(.tag-item.is-selected) {
  background-color: #FF6600 !important;
  border-color: #FF6600 !important;
  color: #ffffff !important;
}

:deep(.tag-item.is-selected:hover) {
  background-color: #ff8533 !important;
  border-color: #ff8533 !important;
  color: #ffffff !important;
}

/* 标签选择对话框专用样式 */
:deep(.tag-select-dialog .el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

:deep(.tag-select-dialog .el-dialog__header) {
  padding: 20px 24px 16px;
  background: #ffffff;
  border-bottom: 1px solid #e8e8e8;
  margin: 0;
}

:deep(.tag-select-dialog .el-dialog__title) {
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

:deep(.tag-select-dialog .el-dialog__headerbtn) {
  top: 16px;
  right: 20px;
}

:deep(.tag-select-dialog .el-dialog__close) {
  color: #999;
  font-size: 18px;
}

:deep(.tag-select-dialog .el-dialog__close:hover) {
  color: #666;
}

:deep(.tag-select-dialog .el-dialog__body) {
  padding: 0;
  max-height: 500px;
  overflow-y: auto;
}

:deep(.tag-select-dialog .el-dialog__footer) {
  padding: 16px 24px 20px;
  background: #fafafa;
  border-top: 1px solid #e8e8e8;
  text-align: right;
}

:deep(.tag-select-dialog .el-dialog__footer .el-button) {
  padding: 8px 20px;
  font-size: 14px;
  font-weight: 500;
  border-radius: 4px;
  margin-left: 8px;
}

:deep(.tag-select-dialog .el-dialog__footer .el-button--primary) {
  background-color: #FF6600;
  border-color: #FF6600;
}

:deep(.tag-select-dialog .el-dialog__footer .el-button--primary:hover) {
  background-color: #ff8533;
  border-color: #ff8533;
}

.rules-link {
  color: #1890ff; // 蓝色，可根据需求修改为其他颜色
  font-size: 14px;
  padding: 0;
  height: auto;
  line-height: inherit;
}

.rules-link:hover {
  color: #40a9ff;
  border-color: transparent;
  background-color: transparent;
}

/* 参赛者规范对话框内容样式 */
.rules-content {
  height: calc(100% - 40px);
  overflow-y: auto;
  padding: 20px;
  line-height: 1.6;
}

.rules-content h1,
.rules-content h2,
.rules-content h3,
.rules-content p {
  margin-bottom: 10px;
}

/* AI工具相关样式 */
.ai-tools-container {
  width: 100%;
}

.ai-tool-first-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.ai-tool-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.ai-tool-input {
  flex: 1;
  margin-right: 10px;
}

.remove-tool-btn {
  height: 40px;
  width: 40px;
  padding: 0;
  margin-left: 10px;
}

.add-tool-btn {
  height: 40px;
  margin-left: 10px;
  background-color: #1890ff;
  border-color: #1890ff;
}

@media screen and (max-width: 768px) {
  .wrapper {
    padding: 15px;
  }


  .upload-tip,
  .design-tip {
    font-size: 11px; // 原12px
  }

  .selected-tags-info {
    font-size: 12px; // 原14px
  }

  .submit-btn {
    font-size: 14px; // 原16px
    width: 100%; // 手机端按钮全屏宽度
  }

  // Element Plus组件文字大小调整
  :deep(.el-form-item__label) {
    font-size: 13px; // 减小标签文字大小
    width: 100% !important;
    margin-right: 0 !important;
    text-align: left !important;
  }

  :deep(.el-input__inner),
  :deep(.el-textarea__inner) {
    font-size: 13px; // 减小输入框文字大小
  }

  :deep(.el-radio__label),
  :deep(.el-checkbox__label) {
    font-size: 13px; // 减小单选和复选框文字大小
  }

  :deep(.el-tag) {
    font-size: 12px; // 减小标签文字大小
  }

  :deep(.el-button) {
    font-size: 13px; // 减小按钮文字大小
  }

  // 确保在移动端标签和输入框垂直排列
  :deep(.el-form-item) {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  :deep(.el-form-item__content) {
    margin-left: 0 !important;
    width: 100%;
  }

  // 对话框文字大小调整
  .dialog-title {
    font-size: 18px; // 原22px
  }

  .tag-section-title {
    font-size: 14px; // 原16px
  }
}

// 添加媒体查询 - 平板端适配
@media screen and (max-width: 1200px) {
  .wrapper {
    width: 98%;
    padding: 20px;
  }


  .submit-btn {
    font-size: 15px; // 原16px
  }
}

:deep(.el-form-item__label) {
  justify-content: flex-start;
}

/* 子级弹窗限制在父级区域内样式 */
:deep(.child-dialog) {
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  width: 100% !important;
  height: 100% !important;
  margin: 0 !important;
  transform: none !important;
  z-index: 2001 !important;
  max-width: 100% !important;
  max-height: 100% !important;
}

:deep(.child-dialog .el-dialog__wrapper) {
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  width: 100% !important;
  height: 100% !important;
  z-index: 2001 !important;
  max-width: 100% !important;
  max-height: 100% !important;
}

:deep(.child-dialog .el-dialog) {
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  width: 100% !important;
  height: 100% !important;
  margin: 0 !important;
  transform: none !important;
  max-width: 100% !important;
  max-height: 100% !important;
  overflow: hidden !important;
}

:deep(.child-dialog .el-dialog__body) {
  height: calc(100% - 120px) !important;
  padding: 20px !important;
  overflow-y: auto !important;
  position: relative !important;
  max-width: 100% !important;
  max-height: calc(100% - 120px) !important;
}

/* 移动端优化 */
@media screen and (max-width: 768px) {
  .tag-dialog-content {
    height: calc(100% - 20px);
    padding: 15px;
  }
  
  .rules-content {
    height: calc(100% - 20px);
    padding: 15px;
  }
  
  :deep(.el-dialog__body) {
    height: calc(100% - 80px) !important;
    padding: 15px !important;
  }
}

/* 用户选择对话框样式 */
:deep(.el-dialog__wrapper) {
  z-index: 2000 !important;
}

:deep(.el-dialog) {
  z-index: 2001 !important;
}

.user-list-container {
  max-height: 400px;
  overflow-y: auto;
}

.no-users {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-size: 14px;
}

  .user-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
    padding: 10px 0;
  }

.user-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  min-height: 80px;
  
  &:hover {
    border-color: #409eff;
    background-color: #f0f9ff;
  }
  
    .user-avatar {
      width: 45px;
      height: 45px;
      border-radius: 50%;
      background-color: #f5f7fa;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 12px;
      overflow: hidden;
      flex-shrink: 0;
    
    .avatar-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .el-icon-user {
      font-size: 16px;
      color: #909399;
    }
  }
  
  .user-info {
    flex: 1;
    
      .user-name {
        font-size: 14px;
        font-weight: 500;
        color: #303133;
        margin-bottom: 4px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      
      .user-id {
        font-size: 12px;
        color: #909399;
        margin-bottom: 2px;
      }
      
      .user-email {
        font-size: 11px;
        color: #c0c4cc;
        margin-top: 2px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
  }
  
  // 评论状态相关样式
  .comment-status-section {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .platform-disabled-tip {
      color: #f56c6c;
      font-size: 12px;
      font-weight: 500;
    }
  }
  
  // 用户分页样式
  .user-pagination {
    margin-top: 20px;
    text-align: center;
    padding: 10px 0;
    border-top: 1px solid #ebeef5;
  }
}

// 自定义对话框样式
:deep(.user-select-dialog) {
  .el-dialog {
    height: 95vh;
    max-height: 120vh;
    display: flex;
    flex-direction: column;
  }
  
  .el-dialog__body {
    flex: 1;
    overflow: hidden;
    padding: 20px;
  }
  
  .user-list-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  
  .user-grid {
    flex: 1;
    overflow-y: auto;
    max-height: calc(95vh - 200px);
    padding: 10px 0;
  }
  
  .user-pagination {
    flex-shrink: 0;
    margin-top: 15px;
    text-align: center;
    padding: 10px 0;
    border-top: 1px solid #ebeef5;
  }
}
</style>

